#!/usr/bin/env python3
"""
MacAgent Pro - Native macOS AI Assistant (Signed)
"""

import os
import sys
import subprocess
import threading
import queue
import time
from datetime import datetime
import logging

# macOS specific imports
try:
    import objc
    from Foundation import NSObject, NSTimer, NSRunLoop, NSDefaultRunLoopMode
    from AppKit import (
        NSApplication, NSStatusBar, NSMenu, NSMenuItem, 
        NSImage, NSAlert, NSWorkspace
    )
except ImportError:
    print("PyObjC not found. Installing...")
    subprocess.check_call([sys.executable, "-m", "pip", "install", "pyobjc-framework-Cocoa"])
    import objc
    from Foundation import NSObject, NSTimer, NSRunLoop, NSDefaultRunLoopMode
    from AppKit import (
        NSApplication, NSStatusBar, NSMenu, NSMenuItem, 
        NSImage, NSAlert, NSWorkspace
    )

# Setup logging
log_dir = os.path.expanduser('~/Library/Logs/MacAgent')
os.makedirs(log_dir, exist_ok=True)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(os.path.join(log_dir, 'macagent.log')),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

class MacAgentApp(NSObject):
    """MacAgent Pro - menubar application"""
    
    def init(self):
        self = objc.super(MacAgentApp, self).init()
        if self is None:
            return None
            
        self.statusbar = NSStatusBar.systemStatusBar()
        self.statusitem = self.statusbar.statusItemWithLength_(-1)  # Variable width
        
        # Set up the status item
        self.statusitem.setTitle_("🤖")
        self.statusitem.setHighlightMode_(True)
        
        # Create menu
        self.menu = NSMenu.alloc().init()
        
        # Menu items
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "MacAgent Pro v1.0.2 - Active", None, "")
        menuitem.setEnabled_(False)
        self.menu.addItem_(menuitem)
        
        self.menu.addItem_(NSMenuItem.separatorItem())
        
        # Voice command item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "Say 'Hey MacAgent'", "processVoiceCommand:", "")
        menuitem.setTarget_(self)
        self.menu.addItem_(menuitem)
        
        # Backup status
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "Check Backup Status", "checkBackupStatus:", "")
        menuitem.setTarget_(self)
        self.menu.addItem_(menuitem)
        
        self.menu.addItem_(NSMenuItem.separatorItem())
        
        # System info
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "System Information", "showSystemInfo:", "")
        menuitem.setTarget_(self)
        self.menu.addItem_(menuitem)
        
        # About
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "About MacAgent Pro", "showAbout:", "")
        menuitem.setTarget_(self)
        self.menu.addItem_(menuitem)
        
        self.menu.addItem_(NSMenuItem.separatorItem())
        
        # Quit
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            "Quit", "quit:", "q")
        menuitem.setTarget_(self)
        self.menu.addItem_(menuitem)
        
        self.statusitem.setMenu_(self.menu)
        
        logger.info("MacAgent Pro v1.0.2 initialized successfully")
        return self
    
    def processVoiceCommand_(self, sender):
        """Process voice command"""
        logger.info("Voice command requested")
        
        alert = NSAlert.alloc().init()
        alert.setMessageText_("Voice Command")
        alert.setInformativeText_("Say 'Hey MacAgent' followed by your command.\n\nSupported commands:\n• 'What time is it?'\n• 'Check backup status'\n• 'Open Terminal'\n• 'Show system info'")
        alert.addButtonWithTitle_("OK")
        alert.runModal()
    
    def checkBackupStatus_(self, sender):
        """Check backup status"""
        try:
            # Check Time Machine
            tm_result = subprocess.run(['tmutil', 'status'], capture_output=True, text=True)
            tm_enabled = tm_result.returncode == 0
            
            # Check if backup destination is available
            dest_result = subprocess.run(['tmutil', 'destinationinfo'], capture_output=True, text=True)
            dest_available = dest_result.returncode == 0
            
            status = f"Time Machine: {'✅ Active' if tm_enabled else '❌ Inactive'}\n"
            status += f"Destination: {'✅ Available' if dest_available else '❌ Not Found'}"
            
            alert = NSAlert.alloc().init()
            alert.setMessageText_("Backup System Status")
            alert.setInformativeText_(status)
            alert.addButtonWithTitle_("OK")
            alert.runModal()
            
            logger.info(f"Backup status checked: TM={tm_enabled}, Dest={dest_available}")
                
        except Exception as e:
            logger.error(f"Error checking backup status: {e}")
    
    def showSystemInfo_(self, sender):
        """Show system information"""
        try:
            # Get system info
            system_info = subprocess.run(['system_profiler', 'SPSoftwareDataType'], 
                                       capture_output=True, text=True)
            
            # Extract key info
            lines = system_info.stdout.split('\n')
            os_version = "Unknown"
            for line in lines:
                if "System Version:" in line:
                    os_version = line.split(":", 1)[1].strip()
                    break
            
            info = f"macOS Version: {os_version}\n"
            info += f"MacAgent Pro: v1.0.2 (Signed)\n"
            info += f"Status: Running in menubar"
            
            alert = NSAlert.alloc().init()
            alert.setMessageText_("System Information")
            alert.setInformativeText_(info)
            alert.addButtonWithTitle_("OK")
            alert.runModal()
            
        except Exception as e:
            logger.error(f"Error getting system info: {e}")
    
    def showAbout_(self, sender):
        """Show about dialog"""
        alert = NSAlert.alloc().init()
        alert.setMessageText_("MacAgent Pro")
        alert.setInformativeText_(
            "Version 1.0.2 (Signed)\n\n"
            "Your private, local AI assistant for macOS.\n"
            "Enhanced with backup monitoring and system integration.\n\n"
            "Features:\n"
            "• Voice control with 'Hey MacAgent'\n"
            "• Backup monitoring and 3-2-1 compliance\n"
            "• Privacy-focused design\n"
            "• Native macOS integration\n"
            "• Code signed for security\n\n"
            "© 2025 MacAgent Systems"
        )
        alert.addButtonWithTitle_("OK")
        alert.runModal()
    
    def quit_(self, sender):
        """Quit the application"""
        logger.info("MacAgent Pro shutting down")
        NSApplication.sharedApplication().terminate_(self)

def main():
    """Main entry point"""
    app = NSApplication.sharedApplication()
    delegate = MacAgentApp.alloc().init()
    app.setDelegate_(delegate)
    app.setActivationPolicy_(1)  # Menubar app only
    app.run()

if __name__ == "__main__":
    main()
